<template>
  <div class="form">
    <SpuUpload
      ref="spuUpload"
      :imageList="data.images"
      @uploadRemove="uploadRemove"
      @uploadSuccess="uploadSuccess"
    />
  </div>
</template>

<script>
import productFormMixins from "@/views/base/productForm";
import jsonUtils from "@/utils/jsonUtils";

import SpuUpload from "./components/spuUpload.vue";

export default {
  name: "spuUpdateImageForm",
  mixins: [productFormMixins],
  props: ["spuInfo"],
  components: {
    SpuUpload,
  },
  data() {
    return {
      init: {
        images: [],
      },
      data: {
        images: [],
      },
    };
  },
  methods: {
    uploadRemove(meta, image) {
      this.data.images = this.data.images.filter(
        (item) => item.sn !== image.sn
      );
      this.$parent.$parent.spuImagesRemove(image);
    },
    uploadSuccess(meta, image) {
      this.data.images.push(image);
      this.$parent.$parent.spuImagesAdd(image, this.data.images.length);
    },
    validate() {
      if(this.data.images.length == 0) {
        this.$message.error("至少需要一张图片");
      }
      return this.data.images.length > 0;
    },
    initData() {
      if (this.spuInfo.images) {
        this.data.images = jsonUtils.deepCopy(this.spuInfo.images);

        // 设置默认图片编号
        this.$refs.spuUpload.setDefaultImageSn(this.spuInfo.defaultSpuImageSn);
      }
    },
    getData() {
      var images = jsonUtils.deepCopy(this.data.images);
      var selectedImageSn = this.$refs.spuUpload.selectedImageSn;

      // 设置默认图片
      var hasDefault = false;
      images.forEach((image) => {
        image.isDefault = 0;
        if (image.sn == selectedImageSn) {
          hasDefault = true;
          image.isDefault = 1;
        }
      });

      // 没有设置，默认选择第一个
      if (!hasDefault) {
        if (images.length > 0) {
          images[0].isDefault = 1;
        }
      }

      // 设置图片排序
      var initSort = 100;
      images.forEach(image => {
        if(image.isDefault == 1) {
          image.sort = 100;
        }else {
          image.sort = ++initSort;
        }
      })
      return images;
    },
  },
};
</script>

<style lang="less" scoped>
.form {
  overflow: auto;
  height: 60vh;
}
</style>